// noinspection JSUnusedGlobalSymbols

import type {AxiosInstance, AxiosRequestConfig} from "axios";
import axios from "axios";
import {showFailToast} from 'vant';

// 定义接口响应的基础类型
interface BaseResponse<T = any> {
    code: number;
    data: T;
    msg: string;
}

// 创建axios实例
const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: 10000,
    headers: {
        "Content-Type": "application/json;charset=utf-8",
        "Cache-Control": "no-cache",
        "Pragma": "no-cache"
    },
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        // 从localStorage获取token
        const token = localStorage.getItem("token");
        if (token) {
            config.headers["Authorization"] = `Bearer ${token}`;
        }
        config.headers["tenant-id"] = 1;
        return config;
    },
    (error) => {
        console.error("请求错误:", error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: any) => {
        const res = response.data;

        // 如果响应没有data字段，可能是直接返回的数据
        if (res.data === undefined && !res.code) {
            return Promise.reject(new Error("响应数据格式错误"));
        }

        // 根据后端约定的状态码判断请求是否成功
        if (res.code !== 0) {
            // 处理token过期
            if (res.code === 401) {
                localStorage.removeItem("token");
                window.location.href = "/";
            }
            showFailToast(res.msg || "未知错误");
            return Promise.reject(new Error(res.msg || "未知错误"));
        }
        return res.data;
    },
    (error) => {
        console.error("响应错误:", error);
        return Promise.reject(error);
    }
);

// 封装GET请求方法
export const get = <T = any>(
    url: string,
    params?: any,
    config?: AxiosRequestConfig
) => {
    return service.get<BaseResponse<T>, T>(url, {params, ...config});
};

// 封装POST请求方法
export const post = <T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
) => {
    return service.post<BaseResponse<T>, T>(url, data, config);
};

// 封装PUT请求方法
export const put = <T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
) => {
    return service.put<BaseResponse<T>, T>(url, data, config);
};

// 封装DELETE请求方法
export const del = <T = any>(url: string, config?: AxiosRequestConfig) => {
    return service.delete<BaseResponse<T>, T>(url, config);
};

export default service;
